<?php
/**
 * 门店文件上传控制器
 * Created by PhpStorm.
 * Author: 芸众商城 www.yunzshop.com
 * Date: 2024/1/1
 * Time: 上午10:00
 */

namespace App\Http\Controllers\Api\store;

use App\Common\Components\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\Api\BaseApiController;

class UploadController extends BaseApiController
{
    protected $publicController = ['Upload'];
    protected $publicAction = ['image', 'file'];
    protected $ignoreAction = [];

    /**
     * 图片上传接口
     * 与前端 el-upload 对接，返回 {status:'success', data:{url}} 结构
     */
    public function image(Request $request)
    {
        if (!$request->hasFile('file')) {
            return $this->errorJson('请提供上传文件');
        }

        $file = $request->file('file');
        $attach = $request->input('attach', '');
        $type = $request->input('type', 'goods'); // 上传类型：goods商品，store门店等

        // 允许类型与大小校验
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $ext = strtolower($file->getClientOriginalExtension());
        if (!in_array($ext, $allowed)) {
            return $this->errorJson('仅支持图片文件（jpg/jpeg/png/gif/webp）');
        }
        
        // 图片大小限制（5MB）
        if ($file->getSize() > 5 * 1024 * 1024) {
            return $this->errorJson('图片大小不能超过5MB');
        }

        // 存储目录按类型和用途归类
        $dir = $this->getUploadDir($type, $attach);
        
        $filename = time() . '_' . uniqid() . '.' . $ext;
        $path = $file->storeAs($dir, $filename, 'public');
        $url = asset('storage/' . $path);

        return $this->successJson('上传成功', [
            'url' => $url,
            'filename' => $filename,
            'original' => $file->getClientOriginalName(),
            'attach' => $attach,
            'type' => $type,
            'size' => $file->getSize()
        ]);
    }

    /**
     * 文件上传接口（支持更多文件类型）
     */
    public function file(Request $request)
    {
        if (!$request->hasFile('file')) {
            return $this->errorJson('请提供上传文件');
        }

        $file = $request->file('file');
        $attach = $request->input('attach', '');
        $type = $request->input('type', 'goods');

        // 允许的文件类型
        $allowedTypes = [
            'image' => ['jpg', 'jpeg', 'png', 'gif', 'webp'],
            'document' => ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'],
            'video' => ['mp4', 'avi', 'mov', 'wmv', 'flv'],
            'audio' => ['mp3', 'wav', 'ogg', 'aac'],
            'archive' => ['zip', 'rar', '7z', 'tar', 'gz']
        ];

        $ext = strtolower($file->getClientOriginalExtension());
        $fileType = $this->getFileType($ext);
        
        if (!$fileType) {
            return $this->errorJson('不支持的文件类型');
        }

        // 文件大小限制
        $maxSize = $this->getMaxSize($fileType);
        if ($file->getSize() > $maxSize) {
            $maxSizeMB = round($maxSize / 1024 / 1024, 1);
            return $this->errorJson("文件大小不能超过{$maxSizeMB}MB");
        }

        // 存储目录
        $dir = $this->getUploadDir($type, $attach, $fileType);
        
        $filename = time() . '_' . uniqid() . '.' . $ext;
        $path = $file->storeAs($dir, $filename, 'public');
        $url = asset('storage/' . $path);

        return $this->successJson('上传成功', [
            'url' => $url,
            'filename' => $filename,
            'original' => $file->getClientOriginalName(),
            'attach' => $attach,
            'type' => $type,
            'file_type' => $fileType,
            'size' => $file->getSize()
        ]);
    }

    /**
     * 批量上传接口
     */
    public function batch(Request $request)
    {
        if (!$request->hasFile('files')) {
            return $this->errorJson('请提供上传文件');
        }

        $files = $request->file('files');
        $type = $request->input('type', 'goods');
        $attach = $request->input('attach', '');
        
        if (!is_array($files)) {
            $files = [$files];
        }

        $results = [];
        $errors = [];

        foreach ($files as $index => $file) {
            try {
                // 图片类型验证
                $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                $ext = strtolower($file->getClientOriginalExtension());
                
                if (!in_array($ext, $allowed)) {
                    $errors[] = "文件 {$file->getClientOriginalName()} 不是支持的图片格式";
                    continue;
                }
                
                if ($file->getSize() > 5 * 1024 * 1024) {
                    $errors[] = "文件 {$file->getClientOriginalName()} 超过5MB限制";
                    continue;
                }

                $dir = $this->getUploadDir($type, $attach);
                $filename = time() . '_' . uniqid() . '_' . $index . '.' . $ext;
                $path = $file->storeAs($dir, $filename, 'public');
                $url = asset('storage/' . $path);

                $results[] = [
                    'url' => $url,
                    'filename' => $filename,
                    'original' => $file->getClientOriginalName(),
                    'size' => $file->getSize()
                ];
            } catch (\Exception $e) {
                $errors[] = "文件 {$file->getClientOriginalName()} 上传失败：" . $e->getMessage();
            }
        }

        return $this->successJson('批量上传完成', [
            'files' => $results,
            'errors' => $errors,
            'success_count' => count($results),
            'error_count' => count($errors)
        ]);
    }

    /**
     * 删除文件接口
     */
    public function delete(Request $request)
    {
        $url = $request->input('url');
        if (empty($url)) {
            return $this->errorJson('请提供文件URL');
        }

        try {
            // 从URL中提取文件路径
            $path = $this->getPathFromUrl($url);
            if (Storage::disk('public')->exists($path)) {
                Storage::disk('public')->delete($path);
                return $this->successJson('文件删除成功');
            } else {
                return $this->errorJson('文件不存在');
            }
        } catch (\Exception $e) {
            return $this->errorJson('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取上传目录
     */
    private function getUploadDir($type, $attach, $fileType = 'image')
    {
        $baseDir = 'uploads';
        
        switch ($type) {
            case 'goods':
                $baseDir .= '/goods';
                break;
            case 'store':
                $baseDir .= '/store';
                break;
            case 'user':
                $baseDir .= '/user';
                break;
            default:
                $baseDir .= '/common';
        }

        // 按文件类型分类
        if ($fileType !== 'image') {
            $baseDir .= '/' . $fileType;
        }

        // 按用途分类
        if ($attach) {
            $baseDir .= '/' . $attach;
        }

        return $baseDir;
    }

    /**
     * 获取文件类型
     */
    private function getFileType($ext)
    {
        $typeMap = [
            'jpg' => 'image', 'jpeg' => 'image', 'png' => 'image', 'gif' => 'image', 'webp' => 'image',
            'pdf' => 'document', 'doc' => 'document', 'docx' => 'document', 'xls' => 'document', 'xlsx' => 'document',
            'mp4' => 'video', 'avi' => 'video', 'mov' => 'video', 'wmv' => 'video',
            'mp3' => 'audio', 'wav' => 'audio', 'ogg' => 'audio',
            'zip' => 'archive', 'rar' => 'archive', '7z' => 'archive'
        ];

        return $typeMap[$ext] ?? null;
    }

    /**
     * 获取文件大小限制
     */
    private function getMaxSize($fileType)
    {
        $limits = [
            'image' => 5 * 1024 * 1024,      // 5MB
            'document' => 10 * 1024 * 1024,   // 10MB
            'video' => 100 * 1024 * 1024,     // 100MB
            'audio' => 20 * 1024 * 1024,      // 20MB
            'archive' => 50 * 1024 * 1024     // 50MB
        ];

        return $limits[$fileType] ?? 5 * 1024 * 1024;
    }

    /**
     * 从URL中提取文件路径
     */
    private function getPathFromUrl($url)
    {
        $parsedUrl = parse_url($url);
        $path = $parsedUrl['path'] ?? '';
        
        // 移除 /storage/ 前缀
        if (strpos($path, '/storage/') === 0) {
            $path = substr($path, 9);
        }
        
        return $path;
    }
}
